package configuration

import (
	"encoding/json"
	"errors"
	"fmt"
	"kop/modules/configuration/client"
	"kop/modules/shop/configuration/refreshtype"
	"kop/util/log"
)

func init() {

	var err error
	var b = client.Load("ShopGoods")
	if err = json.Unmarshal(b, &GoodsConfigs); err != nil {
		panic(err)
	}

	log.Info("Load ShopGoods.json success.")
	//********************************************************************//

	var m = make(map[int32]struct {
		ShopID            int32            `json:"ID"` // 商店ID
		Name              string           // 商店名称
		RefreshType       refreshtype.Type // 刷新类型
		RefreshItemID     int32            // 刷新货币类型
		RefreshItemNumber int32            `json:"RefreshItemCount"` // 刷新货币消耗
		RefreshLimit      int32            // 刷新次数
		Version           int32            // 对比版本是否强制刷新
	})

	b = client.Load("ShopTemplate")
	if err = json.Unmarshal(b, &m); err != nil {
		panic(err)
	}

	for _, v := range m {
		ShopConfigs[v.ShopID] = ShopConf{
			ShopID: v.ShopID,
			Name:   v.Name,
			Refresh: refresh{
				Type:       v.RefreshType,
				Limit:      v.RefreshLimit,
				ItemID:     v.RefreshItemID,
				ItemNumber: v.RefreshItemNumber,
				Version:    v.Version,
			},
		}
	}

	log.Info("Load ShopTemplate.json success.")
}

// 商店配置
type (
	refresh struct {
		Type       refreshtype.Type // 刷新类型
		Limit      int32            // 刷新次数
		ItemID     int32            // 刷新货币类型
		ItemNumber int32            // 刷新货币消耗
		Version    int32            // 对比版本是否强制刷新
	}

	ShopConf struct {
		ShopID  int32   `json:"ID"` // 商店ID
		Name    string  // 商店名称
		Refresh refresh // 刷新类型
	}

	GoodsConf struct {
		GoodsID    int32 `json:"ID"` // 商品ID
		ShopID     int32 // 商店ID
		Group      int32 // 分组ID
		Weight     int32 // 权重：1:10000
		PropID     int32 // 道具|船长|魔戒 ID
		Number     int32 // 堆叠数量
		Limit      int32 // 购买上限
		Level      int32 // 需求爵位
		Vip        int32 // 需求VIP
		NeedItemID int32 // 货币类型
		Price      int32 `json:"CurrentPrice"` // 现价
	}
)

func (c *GoodsConf) SetWeight(w int32) {
	c.Weight = w
}

func (c GoodsConf) GetWeight() int32 {
	return c.Weight
}

func (c GoodsConf) GetID() int32 {
	return c.GoodsID
}

var (
	GoodsConfigs = map[int32]GoodsConf{}
	ShopConfigs  = map[int32]ShopConf{}
)

func GetByGoodsID(goodsID int32) (GoodsConf, error) {

	var conf, ok = GoodsConfigs[goodsID]
	if ok {
		return conf, nil
	}

	return GoodsConf{}, errors.New(fmt.Sprintf("GoodsID not found [%d]", goodsID))
}

func GetGoodsByShopID(shopID int32) []GoodsConf {

	var res []GoodsConf
	for _, v := range GoodsConfigs {
		if v.ShopID == shopID {
			res = append(res, v)
		}
	}

	return res
}

func GetShopByShopID(ID int32) (ShopConf, error) {

	var conf, ok = ShopConfigs[ID]
	if ok {
		return conf, nil
	}

	return ShopConf{}, errors.New(fmt.Sprintf("GoodsID not found [%d]", ID))
}
